<template>
  <div>
    <div class="page-header">
      <div class="box">
        <el-row class="left">
          <el-row class="title">
            <span></span>
            采购单详情
          </el-row>
        </el-row>
        <el-row class="right">
          <el-button type="primary" class="tlwok-btn" @click="reloadPage">
            <span class="el-icon-refresh el-icon--left"></span>刷新
          </el-button>
          <el-button type="danger" class="tlwok-btn" @click="closePage">
            <span class="el-icon-close el-icon--left"></span>关闭
          </el-button>
        </el-row>
      </div>
    </div>
    <div class="page-content">
      <div class="info-box">
        <el-steps
          active="4"
          finish-status="error"
          align-center
          v-if="basicInfo.orderState == 0"
        >
          <el-step
            v-for="step in stepListError"
            :key="step.code"
            icon="el-icon-time"
            :title="step.desc"
            :description="descTime(step.code)"
            :status="step.status"
          ></el-step>
        </el-steps>
        <el-steps
          :active="stepActive"
          finish-status="success"
          align-center
          v-else
        >
          <el-step
            v-for="step in stepList"
            :key="step.code"
            icon="el-icon-time"
            :title="step.desc"
            :description="descTime(step.code)"
          ></el-step>
        </el-steps>
      </div>
      <div class="table-box">
        <div class="table-title">
          <el-row class="left">
            <span class="title">
              采购单编号：{{ basicInfo.purchaseOrderId }}
            </span>
          </el-row>
        </div>
        <div class="info-item base-info">
          <div class="thead">
            <el-row>
              <i class="el-icon-s-management el-icon--left"></i> 采购单基础信息
            </el-row>
          </div>
          <div class="tbody">
            <div class="content">
              <div class="line-item">
                <el-row>
                  <span class="required-icon">*</span>
                  业务员：{{ basicInfo.clientName }}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  业务类型：{{ basicInfo.businessType }}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  采购时间：{{ basicInfo.orderTime }}
                </el-row>
              </div>
              <div class="line-item">
                <el-row>
                  <span class="required-icon">*</span>
                  客户名称：{{ basicInfo.clientUnitName }}
                </el-row>
                <el-row>
                  <span class="required-icon">*</span>
                  收货地址：{{ basicInfo.address }}
                </el-row>
                <el-row> 联系电话：{{ basicInfo.clientPhone }} </el-row>
              </div>
              <div class="line-item">
                <el-row> 下单平台：{{ basicInfo.platformType }} </el-row>
                <el-row> 订单编号：{{ basicInfo.orderId }} </el-row>
                <el-row>备注：{{ basicInfo.remark || '无' }}</el-row>
              </div>
            </div>
          </div>
        </div>
        <div class="info-item product-info">
          <div class="thead">
            <el-row>
              <i class="el-icon-s-management el-icon--left"></i> 采购单商品信息
              <template v-if="basicInfo.orderState != 0">
                <el-popconfirm
                  title="确认批量付款？"
                  @onConfirm="batchPay()"
                  style="margin-left: 20px"
                >
                  <el-button
                    slot="reference"
                    type="primary"
                    size="small"
                    :disabled="selection.length < 1"
                    >批量付款</el-button
                  >
                </el-popconfirm>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  size="small"
                  :disabled="selection.length < 1"
                  @click="batchShip()"
                  v-if="basicInfo.orderState != 99"
                  >批量发货</el-button
                >
                <el-popconfirm
                  title="确认批量收货？"
                  @onConfirm="batchReceipt()"
                  style="margin-left: 10px"
                  v-if="basicInfo.orderState != 99"
                  ><el-button
                    slot="reference"
                    type="primary"
                    size="small"
                    :disabled="selection.length < 1"
                    >批量收货</el-button
                  >
                </el-popconfirm>
                <el-popconfirm
                  title="确认批量开票？"
                  @onConfirm="batchInvoiceing()"
                  style="margin-left: 10px"
                  ><el-button
                    slot="reference"
                    type="primary"
                    size="small"
                    :disabled="selection.length < 1"
                    >批量开票</el-button
                  >
                </el-popconfirm>
              </template>
            </el-row>
            <el-row style="font-weight: normal">
              共<span class="warning-text">{{ totalSize }}条</span
              >商品，合计数量<span class="warning-text">{{ totalNumber }}</span
              >，采购总金额<span class="warning-text"
                >{{ totalPurchasePrice }}元</span
              >，销售总金额<span class="warning-text"
                >{{ totalSalesPrice }}元</span
              >
            </el-row>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            default-expand-all
            :span-method="basicSpanMethod"
            :row-style="{ 'background-color': '#f5f5f5' }"
            @selection-change="onSelectionChange"
            ref="table"
          >
            <el-table-column type="selection" width="45" align="center">
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-table
                  :data="scope.row.goodList"
                  :show-header="false"
                  :span-method="
                    expandSpanMethod.bind(null, scope.row.goodList.length)
                  "
                >
                  <el-table-column width="195" align="center">
                    <template slot-scope="expand">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="expand.row.goodName"
                      ></el-input>
                      <span v-else>{{ expand.row.goodName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template slot-scope="expand">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="expand.row.goodModel"
                      ></el-input>
                      <span v-else>{{ expand.row.goodModel }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template slot-scope="expand">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="expand.row.price"
                      ></el-input>
                      <span v-else>￥{{ expand.row.price }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="80">
                    <template slot-scope="expand">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="expand.row.num"
                      ></el-input>
                      <span v-else>{{ expand.row.num }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template slot-scope="expand">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="expand.row.totalPrice"
                      ></el-input>
                      <span v-else>￥{{ expand.row.totalPrice }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template>
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="scope.row.salePrice"
                      ></el-input>
                      <span v-else>￥{{ scope.row.salePrice }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template>
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.trim="scope.row.supplierName"
                      ></el-input>
                      <span v-else>{{ scope.row.supplierName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="100">
                    <template>{{ scope.row.purchaseSource }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="110">
                    <template>{{ scope.row.invoiceNum }}</template>
                  </el-table-column>
                  <el-table-column align="center">
                    <template>
                      <el-button
                        v-if="scope.row.isEdit"
                        type="text"
                        @click="saveExpand(scope.row)"
                        size="medium"
                      >
                        保存
                      </el-button>
                      <template v-else-if="basicInfo.orderState != 0">
                        <el-row v-if="scope.row.payState == 0">
                          <el-button
                            type="text"
                            size="mini"
                            @click="onPay(scope.row.purchaseOrderId)"
                          >
                            确认付款
                          </el-button>
                        </el-row>
                        <el-row v-if="scope.row.deliveryState == 0">
                          <el-button
                            type="text"
                            size="mini"
                            @click="
                              delivery(
                                scope.row.purchaseOrderId,
                                scope.row.parentPurchaseOrderId
                              )
                            "
                          >
                            确认发货
                          </el-button>
                        </el-row>
                        <el-row v-if="scope.row.invoiceState == 0">
                          <el-button
                            type="text"
                            size="mini"
                            @click="onInvoicing(scope.row.purchaseOrderId)"
                          >
                            确认开票
                          </el-button>
                        </el-row>
                        <el-row
                          v-if="
                            scope.row.deliveryState == 1 &&
                            scope.row.signState == 0
                          "
                        >
                          <el-button
                            type="text"
                            size="mini"
                            @click="
                              onReceipt(
                                scope.row.purchaseOrderId,
                                scope.row.parentPurchaseOrderId
                              )
                            "
                          >
                            确认收货
                          </el-button>
                        </el-row>
                        <el-row
                          v-if="
                            basicInfo.orderState != 99 &&
                            basicInfo.orderState != 0
                          "
                        >
                          <el-button
                            type="text"
                            @click="$set(scope.row, 'isEdit', true)"
                            size="mini"
                          >
                            编辑
                          </el-button>
                        </el-row>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="100">
              <template slot-scope="scope">
                <div class="basicInfoRow">
                  <span>
                    是否开票：{{ scope.row.invoiceState == 1 ? '是' : '否' }}
                  </span>
                  <span>
                    货款是否支付：{{ scope.row.payState == 1 ? '是' : '否' }}
                  </span>
                  <span>
                    是否发货：{{ scope.row.deliveryState == 1 ? '是' : '否' }}
                  </span>
                  <span>物流单号：{{ scope.row.logisticsNo }}</span>
                  <span>
                    是否签收：{{ scope.row.signState == 1 ? '是' : '否' }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" header-align="center" width="100">
            </el-table-column>
            <el-table-column label="单价(元)" header-align="center" width="100">
            </el-table-column>
            <el-table-column label="数量" header-align="center" width="80">
            </el-table-column>
            <el-table-column label="采购金额" header-align="center" width="100">
            </el-table-column>
            <el-table-column label="销售金额" header-align="center" width="100">
            </el-table-column>
            <el-table-column
              label="供应商名称"
              header-align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column label="采购渠道" header-align="center" width="100">
            </el-table-column>
            <el-table-column label="发票编号" header-align="center" width="110">
            </el-table-column>
            <el-table-column label="操作" header-align="center">
            </el-table-column>
          </el-table>
          <div class="table-handler">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="pageSizeArr"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalSize"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="批量发货"
      :visible.sync="batchShipObj.popup"
      width="700"
      :close-on-click-modal="false"
    >
      <el-table
        v-loading="batchShipObj.loading"
        :data="batchShipObj.data"
        :header-cell-style="{
          backgroundColor: '#f5f5f5',
          color: '#333',
          fontWeight: 'bold',
          textAlign: 'center',
        }"
        max-height="500"
        :span-method="batchShipBasicMethod"
        row-class-name="batchShipBasicRow"
      >
        <el-table-column label="商品名称" align="center" width="300">
          <template slot-scope="scope">
            <el-table
              class="batchShipTable"
              :data="scope.row.goodList"
              :show-header="false"
              :span-method="
                batchShipMethod.bind(null, scope.row.goodList.length)
              "
            >
              <el-table-column width="300" align="center">
                <template slot-scope="expand">{{
                  expand.row.goodName
                }}</template>
              </el-table-column>
              <el-table-column width="200" align="center">
                <template slot-scope="expand">{{
                  expand.row.goodModel
                }}</template>
              </el-table-column>
              <el-table-column align="center">
                <template>
                  <el-input
                    placeholder="填写物流单号"
                    v-model.trim="scope.row.logisticsNo"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" align="center" width="200">
        </el-table-column>
        <el-table-column label="物流单号"> </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="batchShipObj.popup = false">
          取 消
        </el-button>
        <el-button type="primary" @click="batchShipSubmit()">确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable eqeqeq */
import {
  confirmShip,
  confirmReceipt,
  confirmInvoicing,
  confirmPay,
  batchConfirmPay,
  batchConfirmInvoiceing,
  batchConfirmReceipt,
  batchConfirmShip,
  editOrder,
} from '@/api/PO'
export default {
  name: 'PODetail',
  data() {
    return {
      purchaseOrderId: null,
      basicInfo: {},
      stepList: [
        { code: 1, desc: '待发货' },
        { code: 2, desc: '待收货' },
        { code: 3, desc: '待确认收货' },
        { code: 4, desc: '已完成' },
      ],
      stepListError: [
        { code: 1, desc: '待发货', status: 'wait' },
        { code: 2, desc: '待收货', status: 'wait' },
        { code: 3, desc: '待确认收货', status: 'wait' },
        { code: 4, desc: '已取消' },
      ],
      totalPurchasePrice: 0,
      totalSalesPrice: 0,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      pageSizeArr: [10, 20, 30, 40],
      totalSize: 0,
      totalNumber: 0,
      selection: [],
      batchShipObj: {
        popup: false,
        loading: false,
        data: [],
      },
    }
  },
  computed: {
    stepActive() {
      let val = 0
      if (this.basicInfo.orderState == 3) {
        val = 3
      } else if (this.basicInfo.orderState == 99) {
        val = 4
      } else val = this.basicInfo.orderState - 1
      return val
    },
  },
  created() {
    this.purchaseOrderId = this.$route.query.id
  },
  methods: {
    reloadPage() {
      location.reload()
    },
    closePage() {
      window.close()
    },
    /**
     * 获取基础信息
     */
    getBasicInfo() {
      this.$axios
        .post(`/api/offline/baseOrderInfo/${this.purchaseOrderId}`)
        .then(res => {
          if (res.success) {
            this.basicInfo = res.result
            this.totalPurchasePrice = this.basicInfo.purchasePrice
            this.totalSalesPrice = this.basicInfo.salePrice
          } else this.$message.error(res.desc)
        })
    },
    /**
     * 获取商品信息
     */
    getGoodsInfo() {
      this.$axios
        .post(`/api/offline/goodInfoList`, {
          parentPurchaseOrderId: this.purchaseOrderId,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        })
        .then(res => {
          if (res.success) {
            this.tableData = res.result.list
            this.$refs.table.doLayout()
            this.totalSize = res.result.total
            this.totalNumber = res.result.skuNum
          } else this.$message.error(res.desc)
        })
    },
    /**
     * 分页-改变展示条数
     */
    changeSize(v) {
      this.pageSize = v
      this.getGoodsInfo()
    },
    /**
     * 分页-翻页
     */
    changePage(v) {
      this.pageNum = v
      this.getGoodsInfo()
    },
    /**
     * 步骤图展示
     */
    descTime(step) {
      let time = ''
      switch (parseInt(step)) {
        case 1:
          time = this.basicInfo.createTime
          break
        case 4:
          time =
            this.basicInfo.orderState == 99 || this.basicInfo.orderState == 0
              ? this.basicInfo.updateTime
              : ''
          break

        default:
          break
      }
      return this.formatDate(time)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNum = 1
      this.getGoodsInfo()
    },
    /**
     * 厂直订单——翻页
     */
    handleCurrentChange(val) {
      this.pageNum = val
      this.getGoodsInfo()
    },
    basicSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) return [1, 10]
    },
    expandSpanMethod(length, { row, column, rowIndex, columnIndex }) {
      if (length > 1 && columnIndex > 4) {
        return [length, 1]
      }
    },
    batchShipBasicMethod({ row, column, rowIndex, columnIndex }) {
      return [1, 3]
    },
    batchShipMethod(length, { row, column, rowIndex, columnIndex }) {
      if (length > 1 && columnIndex > 1) {
        return [length, 1]
      }
    },
    async saveExpand(row) {
      try {
        await editOrder(row)
        row.isEdit = false
        this.$message.success('订单商品信息保存成功')
        this.getBasicInfo()
        this.getGoodsInfo()
      } catch (error) {
        console.error(error)
      }
    },
    onSelectionChange(val) {
      this.selection = val
    },
    delivery(purchaseOrderId, parentPurchaseOrderId) {
      this.$prompt('请填写物流单号', '确认发货', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async ({ value }) => {
          try {
            await confirmShip({
              purchaseOrderId,
              parentPurchaseOrderId,
              logisticsNo: value,
            })
            this.$message.success('确认发货成功')
            this.getBasicInfo()
            this.getGoodsInfo()
          } catch (error) {
            console.error(error)
          }
        })
        .catch(() => {})
    },
    onReceipt(purchaseOrderId, parentPurchaseOrderId) {
      this.$confirm('确认收货？').then(async () => {
        try {
          await confirmReceipt({ purchaseOrderId, parentPurchaseOrderId })
          this.$message.success('确认收货成功')
          this.getBasicInfo()
          this.getGoodsInfo()
        } catch (error) {
          console.error(error)
        }
      })
    },
    onInvoicing(purchaseOrderId) {
      this.$prompt('请填写发票编号', '确认开票', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async ({ value }) => {
          try {
            await confirmInvoicing({
              purchaseOrderId,
              invoiceNum: value,
            })
            this.$message.success('确认开票成功')
            this.getBasicInfo()
            this.getGoodsInfo()
          } catch (error) {
            console.error(error)
          }
        })
        .catch(() => {})
    },
    onPay(purchaseOrderId) {
      this.$confirm('确认付款？').then(async () => {
        try {
          await confirmPay({ purchaseOrderId })
          this.$message.success('确认付款成功')
          this.getBasicInfo()
          this.getGoodsInfo()
        } catch (error) {
          console.error(error)
        }
      })
    },
    async batchPay() {
      let arr = []
      this.selection.map(item => {
        if (item.payState == 0)
          arr.push({
            purchaseOrderId: item.purchaseOrderId,
            parentPurchaseOrderId: item.parentPurchaseOrderId,
          })
      })
      if (arr.length < this.selection.length) {
        this.$message.error('勾选项内存在已付款的子订单')
        return
      }
      try {
        await batchConfirmPay(arr)
        this.$message.success('批量付款成功')
        this.getBasicInfo()
        this.getGoodsInfo()
      } catch (error) {
        console.error(error)
      }
    },
    async batchInvoiceing() {
      let arr = []
      this.selection.map(item => {
        if (item.invoiceState == 0)
          arr.push({
            purchaseOrderId: item.purchaseOrderId,
            parentPurchaseOrderId: item.parentPurchaseOrderId,
          })
      })
      if (arr.length < this.selection.length) {
        this.$message.error('勾选项内存在已开票的子订单')
        return
      }

      this.$prompt('请填写发票编号', '确认批量开票', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async ({ value }) => {
          arr.map(item => (item.invoiceNum = value))
          try {
            await batchConfirmInvoiceing(arr)
            this.$message.success('批量开票成功')
            this.getBasicInfo()
            this.getGoodsInfo()
          } catch (error) {
            console.error(error)
          }
        })
        .catch(() => {})
    },
    async batchReceipt() {
      let arr = []
      this.selection.map(item => {
        if (item.orderState == 2)
          arr.push({
            purchaseOrderId: item.purchaseOrderId,
            parentPurchaseOrderId: item.parentPurchaseOrderId,
          })
      })
      if (arr.length < this.selection.length) {
        this.$message.error('勾选项内存在已收货的子订单')
        return
      }
      try {
        await batchConfirmReceipt(arr)
        this.$message.success('批量收货成功')
        this.getBasicInfo()
        this.getGoodsInfo()
      } catch (error) {
        console.error(error)
      }
    },
    batchShip() {
      let arr = []
      this.selection.map(item => {
        if (item.orderState == 1) arr.push(item)
      })
      if (arr.length < this.selection.length) {
        this.$message.error('勾选项内存在已发货的子订单')
        return
      }
      this.batchShipObj.popup = true
      this.batchShipObj.data = arr
    },
    async batchShipSubmit() {
      let param = []
      this.batchShipObj.data.map(item => {
        param.push({
          purchaseOrderId: item.purchaseOrderId,
          parentPurchaseOrderId: item.parentPurchaseOrderId,
          logisticsNo: item.logisticsNo,
        })
      })
      try {
        await batchConfirmShip(param)
        this.$message.success('批量发货成功')
        this.getBasicInfo()
        this.getGoodsInfo()
        this.batchShipObj.popup = false
      } catch (error) {
        console.error(error)
      }
    },
  },
  mounted() {
    this.getBasicInfo()
    this.getGoodsInfo()
  },
}
</script>

<style lang="less" scoped>
@themeColor: #298df8;
.page-header {
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  .box {
    margin: auto;
    width: 1440px;
    height: 65px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 38px;
  }
  .title {
    font-size: 16px;
    font-weight: bold;
    span {
      width: 0;
      height: 20px;
      border: 2px solid @themeColor;
      background: @themeColor;
      margin-right: 14px;
    }
  }
}
.page-content {
  background: #fff;
  padding-top: 65px;
}
.info-box {
  margin: 30px auto;
  width: 60%;
}
.table-box {
  width: 1078px;
  margin: auto;
  padding-bottom: 30px;
}
.table-title {
  border: 1px solid #bbb;
  padding: 0 25px;
  height: 45px;
  display: flex;
  align-items: center;
  background: #e4e4e4;
  justify-content: space-between;
  .left {
    display: flex;
  }
  .title {
    font-weight: bold;
    margin-right: 50px;
  }
}
.info-item {
  border: 1px solid #bbb;
  border-top: 0;
  .thead {
    background: #f5f5f5;
    padding: 0 25px;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: bold;
    .info {
      margin-right: 100px;
    }
  }
}
.base-info {
  .tbody {
    border-top: 1px solid #bbb;
    padding: 25px;
  }
  .content {
    width: 85%;
    margin: 0 auto;
  }
  .line-item {
    display: flex;
    align-items: flex-start;
    .el-row {
      flex: 1;
      margin-bottom: 12px;
      line-height: 28px;
      padding-right: 10px;
      &:first-child {
        margin-right: 50px;
      }
    }
  }
}

.table-handler {
  padding: 5px 15px;
  background-color: #fff;
  text-align: right;
}
.basicInfoRow {
  display: flex;
  justify-content: space-between;
  span {
    padding: 0 10px;
  }
}
</style>
<style lang="less" >
.product-info .el-table__expanded-cell[class*='cell'],
.batchShipBasicRow > td {
  padding: 0;
}
.el-table.batchShipTable::before {
  height: 0;
}
</style>